package com.example.demo.ThreadSafe;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

@Slf4j(topic = "c.Pipe")
public class Pipe {
    public static void main(String[] args) throws IOException, InterruptedException {
        PipedWriter writer = new PipedWriter();
        PipedReader reader = new PipedReader();
        writer.connect(reader); // 这里注意一定要连接，才能通信

        Thread t1 = new Thread(() -> {
            log.debug("this is reader");
            int receive = 0;
            try {
                while ((receive = reader.read()) != -1) {
                    log.debug((char) receive + "");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }, "reader");

        t1.join(1000);


        Thread.sleep(1000);

        new Thread(()->{
            log.debug("this is writer");
            int receive = 0;
            try {
                writer.write("test");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        },"writer").start();
    }
}